package inits

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"video_server/basic/config"
)

func init() {
	InitViper()
	InitMysql()
	InItRedis()
}
func InitViper() {
	viper.SetConfigFile("../video_server/dev.yaml")
	err := viper.ReadInConfig()
	if err != nil {
		panic("viper读取失败")
	}
	log.Println("viper读取成功")
	err = viper.Unmarshal(&config.AppConf)
	if err != nil {
		panic("viper解析失败")
	}
	log.Println("viper解析成功", config.AppConf)
}
func InitMysql() {
	AppConf := config.AppConf.Mysql
	var err error
	dsn := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=utf8mb4&parseTime=True&loc=Local", AppConf.User, AppConf.Password, AppConf.Host, AppConf.Port, AppConf.Database)
	config.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("mysql连接失败")
	}
	log.Println("mysql连接成功", dsn, config.DB)
}
func InItRedis() {
	AppConf := config.AppConf.Redis
	ctx := context.Background()
	config.Rdb = redis.NewClient(&redis.Options{
		Addr:     AppConf.Addr,     // use default Addr
		Password: AppConf.Password, // no password set
		DB:       AppConf.Db,       // use default DB
	})
	result, err := config.Rdb.Ping(ctx).Result()
	if err != nil {
		panic("redis连接失败")
	}
	log.Println("redis连接成功", result, config.Rdb)
}
